﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using A2DFramework.InstanceService;
using A2DFramework.LockService.Providers;

namespace A2DFramework.LockService.Configuration
{
    public static class LockServiceConfiguration
    {
        public static RedisSettings RedisSettings;
        public static LockType LockType;
        private static bool loaded = false;

        static LockServiceConfiguration()
        {
            if (!loaded)
                _Load();
        }

        public static void Load()
        {
            if (!loaded)
                _Load();
        }

        public static void _Load()
        {
            loaded = true;

            XElement root = XElement.Load(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "A2D.config"));

            root = root.Element("LockConfig");
            if (root == null)
                throw new Exception("LockConfig node not exists");


            if (root.Attribute("LockType").Value.Equals("Redis", StringComparison.OrdinalIgnoreCase))
            {
                root = root.Element("Redis");

                LockType = Configuration.LockType.Redis;

                RedisSettings setting = new RedisSettings();

                setting.ReadWriteServerIps = new List<string>();
                setting.ReadOnlyServerIps = new List<string>();

                {
                    string[] serverIps = root.Element("ReadWriteServerIps").Value.Trim().Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    if (serverIps != null)
                        setting.ReadWriteServerIps = serverIps.ToList();
                }
                {
                    string[] serverIps = root.Element("ReadOnlyServerIps").Value.Trim().Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    if (serverIps != null)
                        setting.ReadOnlyServerIps = serverIps.ToList();
                }

                setting.MaxReadPoolSize = int.Parse(root.Element("MaxReadPoolSize").Value);
                setting.MaxWritePoolSize = int.Parse(root.Element("MaxWritePoolSize").Value);
                setting.LockPrefix = root.Element("Prefix").Value;

                RedisSettings = setting;
            }
            else
            {
                throw new Exception("LockSetting LockType属性值必须为Redis");
            }
        }
    }
}
